#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
	QMainWindow(parent),
	ui(new Ui::MainWindow) {
	ui->setupUi(this);
}

MainWindow::~MainWindow() {
	delete ui;
}

void MainWindow::downloadList() {
	//clear current list
	ui->list->clear();

	//create a QNetworkAccessManager and connects it
	QNetworkAccessManager* mNetworkManager = new QNetworkAccessManager(this);
	connect(mNetworkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(downloadListFinished(QNetworkReply*)));

	//number of pages
	int pagesToFetch = ui->nresults->value()/30;

	for (int i=0; i<pagesToFetch; i++) {
		QString urls = QString("http://thepiratebay.org/search/%2/%1/99/100,200,300,400,600/").arg(i).arg(ui->keywords->text());
		qDebug()<<urls;
		QUrl url = urls;
		mNetworkManager->get(QNetworkRequest(url));
	}
}

void MainWindow::downloadListFinished(QNetworkReply* reply) {
	QString replyString;
	if(reply->error() == QNetworkReply::NoError) {
		int httpstatuscode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toUInt();
		if (httpstatuscode == 200) {
			if (reply->isReadable()) {
				//Assuming this is a human readable file replyString now contains the file
				replyString = QString::fromUtf8(reply->readAll().data());
				QList<Link> links = parseForLinks(replyString);
				addLinksToList(links);
			}
		}
	}
}

QList<Link> MainWindow::parseForLinks(QString str) {
	QList<Link> links;

	//remove everything before "<table id="searchResult">"
	str = str.remove(0, str.indexOf("<table id=\"searchResult\">"));

	//remove erything after the end of this </table>
	int idx = str.indexOf("</table>");
	str = str.remove(idx, str.length()-idx);

	//parse every <div class="detName">
	QStringList sections = str.split("<div class=\"detName\">");
	for(int i=1; i<sections.count(); i++) {
		qDebug()<<"------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------";
		Link l;
		//retrieve torrent link
		l.link = sections.at(i);
		l.link = l.link.remove(0, l.link.indexOf("http://"));
		l.link.truncate(l.link.indexOf(".torrent")+8);

		//copy link to description and transform it
		l.desc = l.link.remove(0, l.link.lastIndexOf("/")+1);
		l.desc = l.desc.left(l.desc.indexOf("."));
		l.desc.replace("_", " ");
		qDebug()<<l.desc;

		//retrieve description
		QString desc = sections.at(i);
		desc = desc.remove(0, desc.indexOf("<font class=\"detDesc\">")+22);
		desc.truncate(desc.indexOf("iB, ")+2);
		desc.replace("&nbsp;", " ");

		QStringList date_and_size;
		date_and_size = desc.split(", ");
		QStringList date = date_and_size.at(0).split(" ");
		l.date = QDate::fromString(date.at(1), "MM-dd");

		//there is no "year" field, add it manually
		l.date = QDate(QDate::currentDate().year(), l.date.month(), l.date.day());

		l.time = QTime::fromString(date.at(2), "hh:mm");
		qDebug()<<l.date.toString("dd/MM/2011");
		qDebug()<<l.time.toString("hh.mm");

		links.append(l);
	}
	qDebug()<<QString("Inserted %1 links").arg(links.count());
	return links;
}

class MyDelegate : public  QStyledItemDelegate {

public:
	enum datarole {headerTextRole = Qt::UserRole + 100,subHeaderTextrole = Qt::UserRole+101,IconRole = Qt::UserRole+102};
	MyDelegate(QObject *parent=0) : QStyledItemDelegate (parent){


	}

	void paint ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const {
		QStyledItemDelegate::paint(painter,option,index);

		painter->save();

		QFont font = QApplication::font();
		QFont SubFont = QApplication::font();
		font.setBold(true);
		SubFont.setWeight(SubFont.weight()-2);
		QFontMetrics fm(font);

		QIcon icon = qvariant_cast<QIcon>(index.data(IconRole));
		QString headerText = qvariant_cast<QString>(index.data(headerTextRole));
		QString subText = qvariant_cast<QString>(index.data(subHeaderTextrole));

		QSize iconsize = icon.actualSize(QSize(100, 100));

		QRect headerRect = option.rect;
		QRect subheaderRect = option.rect;
		QRect iconRect = subheaderRect;

		iconRect.setRight(iconsize.width()+30);
		iconRect.setTop(iconRect.top()+5);
		headerRect.setLeft(iconRect.right());
		subheaderRect.setLeft(iconRect.right());
		headerRect.setTop(headerRect.top()+5);
		headerRect.setBottom(headerRect.top()+fm.height());

		subheaderRect.setTop(headerRect.bottom()+2);

		painter->drawPixmap(QPoint(iconRect.left(),iconRect.top()), icon.pixmap(iconsize.width(),iconsize.height()));

		painter->setFont(font);
		painter->drawText(headerRect, Qt::TextWordWrap, headerText);

		painter->setFont(SubFont);
		painter->drawText(subheaderRect.left(),subheaderRect.top()+17, subText);

		painter->restore();
	}

	QSize sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const{
		return QSize(200, 100);
	}
};


void MainWindow::addLinksToList(QList<Link> links) {
	int n = links.count();
	for (int i = 0; i<n; i++) {
		QListWidgetItem *item = new QListWidgetItem();
		QIcon icon(":/piratebay/download.png");
		item->setData(MyDelegate::headerTextRole, links.at(i).link);
		QString str("Added %1 - %2");
		str = str.arg(links.at(i).date.toString("dd/MM/yyyy")).arg(links.at(i).time.toString("hh.mm.ss"));
		item->setData(MyDelegate::subHeaderTextrole, str);
		item->setData(MyDelegate::IconRole, icon);
//		ui->list->addItem(item);
	}
	ui->list->setItemDelegate(new MyDelegate());
}


void MainWindow::downloadItem(QListWidgetItem* item) {
	if (ui->apikey->text().length()==0) {
		QMessageBox::critical(this, "Error", "You must specify your api key!");
		ui->apikey->setFocus();
		return;
	}
	if (ui->apisecret->text().length()==0) {
		QMessageBox::critical(this, "Error", "You must specify your api secret!");
		ui->apisecret->setFocus();
		return;
	}

	ui->list->setEnabled(false);
	ui->statusBar->showMessage("Adding torrent to put.io...");
	QApplication::changeOverrideCursor(Qt::WaitCursor);
	QString link = item->data(MyDelegate::headerTextRole).toString();
	lastLink = link;
	lastItem = item;
	QNetworkAccessManager* mNetworkManager = new QNetworkAccessManager(this);
	connect(mNetworkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(putDotIOResponded(QNetworkReply*)));

	QUrl url = QString("http://api.put.io/v1/transfers?method=add&request={\"api_key\":\"%2\",\"api_secret\":\"%3\",\"params\":{\"links\":{\"url\":\"%1\"}}}").arg(link).arg(ui->apikey->text()).arg(ui->apisecret->text());
	mNetworkManager->get(QNetworkRequest(url));
}

void MainWindow::putDotIOResponded(QNetworkReply* reply) {
	QString answer = QString::fromUtf8(reply->readAll().data());
	if (answer.contains("\"error\": false")) {
		ui->statusBar->showMessage(QString("Successfully added %1").arg(lastLink));
//		ui->list->removeItemWidget(lastItem);
	}
	else ui->statusBar->showMessage(QString("ERROR WHILE ADDING %1").arg(lastLink));

	ui->list->setEnabled(true);
	QApplication::restoreOverrideCursor();
}

void MainWindow::setAPIKey(QString str) {
	ui->apikey->setText(str);
}

void MainWindow::setAPISecret(QString str) {
	ui->apisecret->setText(str);
}

QString MainWindow::getAPIKey() {
	return ui->apikey->text();
}

QString MainWindow::getAPISecret() {
	return ui->apisecret->text();
}

/*
Typical response:
{"response": {"total": 1, "results": [{"status": "Downloading", "percent_done": 0, "name": "The Beatles"}]}, "error": false, "user_name": "deadbird", "id": 4537}
*/
